package apt.dao;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import apt.bean.RoleBean;
import apt.common.HibernateUtil;

import com.sun.xml.internal.ws.handler.HandlerException;

public class RoleDao {
	private ArrayList<RoleBean> arrRoleBeans;
	private Session session;
	private Transaction transaction;
	public RoleDao() {
		arrRoleBeans = new ArrayList<>();
	}

	public ArrayList<RoleBean> getRole() {
		session = HibernateUtil.getSessionFactory().openSession();
		try {
			String sql = "FROM RoleBean";
			Query query = session.createQuery(sql);
			@SuppressWarnings("unchecked")
			List<RoleBean> listRoleBeans = query.list();
			for (Iterator<RoleBean> iterator = listRoleBeans.iterator(); iterator
					.hasNext();) {
				arrRoleBeans.add((RoleBean) iterator.next());
			}

			return arrRoleBeans;
		} catch (HandlerException e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return null;
	}

	public boolean addRole(RoleBean role) {
		session = HibernateUtil.getSessionFactory().openSession();
		try {
			transaction = session.beginTransaction();
			session.save(role);
			transaction.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return true;
	}
	
	public boolean updateRole(RoleBean role) {
		session = HibernateUtil.getSessionFactory().openSession();
		try {
			transaction = session.beginTransaction();
			session.update(role);
		} catch (Exception e) {
			transaction.rollback();
		} finally {
			transaction.commit();
			session.close();
		}
		return true;
	}

}
